package com.github.yoojia.flow.impl;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.Event;
import com.github.yoojia.flow.Payload;
import com.github.yoojia.flow.devices.VirtualDigitOutputDevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数字信号开关型设备
 * @author 陈小锅 (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public class PiSwitchDigitOutputDevice extends VirtualDigitOutputDevice {

    private static final Logger LOGGER = LoggerFactory.getLogger(PiSwitchDigitOutputDevice.class);

    @Override
    public Event handleEvent(Context context, Event request) {
        final Payload.Bool state = request.getBoolPayload();
        if (state.bool){ // ON
            setStateOf(false);
        }else{ // OFF
            setStateOf(true);
        }
        if (isLoggingEnabled()){
            LOGGER.debug("Handling, uuid: {}, OnOff: {}, State: {}",
                    getAddress(),
                    (state.bool ? "ON" : "OFF"),
                    getDigitPin().getState().isHigh() ? "HIGH" : "LOW");
        }
        return Event.simple(request.sequence, Context.TOPIC_SYS_NORESP);
    }

    private void setStateOf(boolean isOff){
        // High is OFF
        if (getOffState().isHigh()){
            if (isOff){
                setHigh();
            }else{
                setLow();
            }
        }else{// else: Low is OFF
            if (isOff){
                setLow();
            }else{
                setHigh();
            }
        }
    }

}
